<?php
/**
 * (commands) Business
 */
namespace App\Console\Commands\SpApi\Report\CreateAndGet;

use App\Logic\Amazon\Api\Report;
use App\Logic\Amazon\Api\RequiredConfig;
use App\Models\Basics\AmazonAccount;
use Illuminate\Console\Command;
class SalesAndTraffic extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sp-report:create-business {date=null} {accountId=0}';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'exe func';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $date = $this->argument('date');
        $accountId = $this->argument('accountId');
        $reportType = 'GET_SALES_AND_TRAFFIC_REPORT';

        $currdate = date('Y-m-d',strtotime('-2 days'));
        if (strtotime($date)) {
            if (strtotime($date) > strtotime($currdate)) {
                dd('date param error!');
            }
        }else{
            $date = $currdate;
        }

        $this->createReport($date,$reportType,$accountId); //创建报告
        $this->info('finish!');
    }

    /**
     * 创建报告
     * @param null $date
     * @param null $reportType
     * @param int $accountId
     * @throws \Throwable
     */
    private function createReport($date = null, $reportType = null, $accountId = 0){

        $eof = $date;
        $accounts = AmazonAccount::_getAccounts($accountId);
        foreach ($accounts as $account){
            $requiredConfig = RequiredConfig::getInit();
            $config = $requiredConfig->configuration($account->refresh_token,$account->aws_region);
            $marketplace_ids = $account->account_country->pluck('marketplace_id')->toArray();

            $time = strtotime($date);
            while (true){
                if($time > strtotime($eof)) break;

                $paramDate = date('Y-m-d',$time);
                echo '------start:'.$paramDate.'-'.$account->account.'（'.$account->id.'）------'.PHP_EOL;
                $data = [
                    'report_options' => [
                        'dateGranularity' => 'DAY',
                        'asinGranularity' => 'CHILD'
                    ],
                    'data_start_time' => $paramDate,
                    'data_end_time' => $paramDate,
                    'report_type' => $reportType
                ];
                Report::apiCreateReport($config,$account,$data,$marketplace_ids,true,1);

                $time += 86400;
                sleep(5);
            }
            sleep(10);
        }
    }

}
